
var gTotalTests = null;
var gOKTests = null;
var gFailedTests = null;
var g_is_done_off = false;
var done_for_the_first_time = true;

$(document).ready(function()
  { 
	
	$("#right-nav").fadeIn();
		
	setTimeout(start_polling,2000);
	
	  (function() {
		    
		  var bar = $('#filebar');
		  var percent = $('#filepercent');
		  var status = $('#filestatus');
		     
		  $('#uploadForm').ajaxForm({
		      beforeSend: function() {
		          status.empty();
		          var percentVal = '0%';
		          bar.width(percentVal);
		          percent.html(percentVal);
		          $("#fileprogress").show();
		          $("#uploadForm").fadeOut("fast");
		      },
		      uploadProgress: function(event, position, total, percentComplete) {
		          var percentVal = percentComplete + '%';
		          bar.width(percentVal);
		          percent.html(percentVal);
		      },
		  	complete: function(xhr) {
		  		$('#status-title').off('click');
		  		$("#status-title").removeAttr('href');
		  		$("#fileprogress").hide();
		  		$("#divUploadFileContainer").fadeOut();
		  		show_status_message("upload complete");
		  		handle_initial("");
		  	},
		     
		  }); 

		  })();
  });


function update_dash(num_total, num_ok, num_failed)
{
	if (num_total != null)
		gTotalTests.refresh(num_total);
	if (num_ok != null)
		gOKTests.refresh(num_ok);
	if (num_failed!=null)
		gFailedTests.refresh(num_failed);
}

function init_tests_dash(num_of_tests)
{
	var new_max = parseInt(num_of_tests);
	
	gTotalTests = new JustGage({
        id: "gTotalTests", 
        value: 0, 
        min: 0,
        max: new_max,
        title: "Total number of tests",
        label: "",
        levelColors: [
                      "#3366CC",
                      "#3366CC",
                      "#3366CC"
                    ] 
      });
	
	gOKTests = new JustGage({
        id: "gOKTests", 
        value: 0, 
        min: 0,
        max: new_max,
        title: "Passed",
        label: "",
        levelColors: [
                      "#00FF33",
                      "#00FF33",
                      "#00FF33"
                    ] 
      });
	
	gFailedTests = new JustGage({
        id: "gFailedTests", 
        value: 0, 
        min: 0,
        max: new_max,
        title: "Failed",
        label: "",
        levelColors: [
                      "#FF0033",
                      "#FF0033",
                      "#FF0033"
                    ] 
      });
	
	}

function pool_func(url_str)
{
	$.ajax({ url: url_str,
		dataType: "xml",
		cache: false,
		timeout: 10000,
		success: function(response) {
				hide_error_message();
				parse_response(response);
			},
	    error: function(x, t, m) {
	    	$("#right-nav-top").html("<p> oops :(</p>");
    		$("#status-title").html("");
    		show_error_message("you're experiencing connection issues..");
	    	}
		});
}

function start_polling()
{
	pool_func("home?action=status");
	setInterval(function(){pool_func("home?action=status");}, 3000);
}

function parse_response(data)
{
	$(data).find("status").each(function () {
		 var text = $(this).text();
		 text = text.trim();
		 if (text=='NEW') {handle_new(data);}
		 if (text=='INITIAL') {handle_initial(data);}
		 if (text=='ANALYZING') {handle_analyzing(data);}
		 if (text=='RUNNING') {handle_running(data);}
		 if (text=='DONE') {handle_done(data);}
		 if (text=='ERROR') {handle_error(data);}
		 });
}


function handle_new(data)
{
	g_is_done_off = false;
	done_for_the_first_time = true;
	$("#right-nav-top").html("<p>Get Started</p>");
	$("#status-title").html("upload your tests JAR file");
	$("#status-title").attr("href","#");
	
	$("#status-title").click(function(){
		  $("#uploadForm").show();
		  $("#fileprogress").hide();
		  $("#divUploadFileContainer").fadeIn();
		  return false;
	  }); 
}

function notify_new_server()
{
	$('#status-title').off('click');
	$("#divTestsProgress").fadeOut();
	pool_func("home?action=init");
	
	gTotalTests = null;
	gOKTests = null;
	gFailedTests = null;
	
	$('#gTotalTests').html("");
	$('#gFailedTests').html("");
	$('#gOKTests').html("");
	
	$("#content-results").html("");
	$("#content-results").accordion("destroy");
	$("#content-results").fadeOut();
	$("#content-about-project").fadeIn();
	return false;
}

function handle_initial(data)
{
	$("#right-nav-top").html("<p>Working</p>");
	$("#status-title").html('<img src="images/loadingjob.gif"/> your job is initializing');
}

function handle_analyzing(data)
{
	$("#status-title").html('<img src="images/loadingjob.gif"/> analyzing your project');
}

function handle_running(data)
{
	$("#status-title").html('<img src="images/loadingjob.gif"/> your tests are running');
	
	var total = $(data).find("numTotal").text();
	var ok = $(data).find("numOK").text();
	var failed = $(data).find("numFail").text();

	if (total == "")
		total = 0;
	if (ok == "")
		ok = 0;
	if (failed == "")
		failed = 0;
	
	show_tests_dash_board(total, ok, failed);
}


function show_tests_dash_board(total, ok, failed)
{
	if (gTotalTests==null)
	{
		init_tests_dash(total);
		$("#divTestsProgress").fadeIn();
		update_dash(parseInt(ok)+parseInt(failed), ok, failed);
	}
	else
	{
		update_dash(parseInt(ok)+parseInt(failed), ok, failed);
	}
}

function handle_done(data)
{
	if (g_is_done_off == true)
		return;
	
	$("#status-title").attr("href","#");
	$("#right-nav-top").html("<p>Done</p>");
	$("#status-title").html("see your test results");
	
	var total = $(data).find("numTotal").text();
	var ok = $(data).find("numOK").text();
	var failed = $(data).find("numFail").text();
	
	if (total == "")
		total = 0;
	if (ok == "")
		ok = 0;
	if (failed == "")
		failed = 0;
	
	show_tests_dash_board(total, ok, failed);
	
	if (done_for_the_first_time)
		{
		show_status_message("all done");
		$("#status-title").click(function(){
				g_is_done_off = true;
			 	show_results();
			 	$("#status-title").html("start a new job");
			 	$("#status-title").click(notify_new_server);
			 	return false;
		  });
		
		done_for_the_first_time = false;
		}
	
}

function show_results()
{
	$('#status-title').off('click');
	$("#content-results").show();
	
	$("#content-about-project").hide();
	
	$.ajax({ url: "home?action=show-results",
		dataType: "html",
		cache: false,
		timeout: 20000,
		success: function(data) {
			$("#content-results").html(data);
			$("#content-results").accordion({
				autoHeight: false,
				navigation: true
			});
			},
	    error: function(x, t, m) {
	    	show_error_message("you're experiencing connection issues..");
	    	}
		});
}

function handle_error(data)
{
	show_error_message("error");
}


function hide_error_message(msg)
{
	$("#nav-top-error").hide("fast");
}

function show_error_message(msg)
{
	$("#nav-top-error").html(msg);
	$("#nav-top-error").slideDown("fast").delay(5000).slideUp("fast");
}

function show_status_message(msg)
{
	$("#nav-top-status").html(msg);
	$("#nav-top-status").slideDown("fast").delay(2000).slideUp("fast");
}

function get_trace(test_id)
{
	var splits=test_id.split("-");
	var test_name = splits[1];
	var class_name = splits[0];
	class_name = class_name.replace("/",".");
	class_name = class_name.substring(0,class_name.length-6);
	
	$("#content-diaglog").html("<img src='images/loadingjob.gif'/> loading");
	$("#content-diaglog").dialog({
        resizable: true,
        modal: true,
        width: 800,
        height: 400,
        title: "Trace for "+test_name+" ("+class_name+")"});
	
	$.ajax({ url: "home?action=show-test-trace&test-id="+test_id,
		dataType: "html",
		cache: false,
		timeout: 20000,
		success: function(data) {
			$("#content-diaglog").html(data);		
			},
	    error: function(x, t, m) {
	    	show_error_message("you're experiencing connection issues..");
	    	}
		});
}